import React, { useState, useCallback, useEffect, useRef, memo, useMemo } from 'react';
import { useUniversalNotification } from '../contexts/UniversalNotificationContext';
import { NotificationState, UniversalNotification } from '../types/notification';
import './DynamicIslandNotification.css';

// 组件Props接口
interface DynamicIslandNotificationProps {
  className?: string;
  style?: React.CSSProperties;
  maxNotifications?: number;
  enableCarousel?: boolean;
  enableTimeDisplay?: boolean;
  enableHoverExpansion?: boolean;
  enableClickExpansion?: boolean;
  autoCollapseDelay?: number;
  theme?: 'auto' | 'light' | 'dark';
  onRemoveNotification?: (id: string) => void;
}

const DynamicIslandNotification: React.FC<DynamicIslandNotificationProps> = ({
  className = '',
  style = {},
  maxNotifications = 10,
  enableCarousel = true,
  enableTimeDisplay = true,
  enableHoverExpansion = true,
  enableClickExpansion = false,
  autoCollapseDelay = 3000,
  theme = 'auto',
  onRemoveNotification,
}) => {
  const { notifications, activeNotifications, persistentNotifications } = useUniversalNotification();
  const [isHovered, setIsHovered] = useState(false);
  const [isForceExpanded, setIsForceExpanded] = useState(false);
  const [currentTime, setCurrentTime] = useState(new Date());
  const [currentCarouselIndex, setCurrentCarouselIndex] = useState(0);
  const [isCarouselAnimating, setIsCarouselAnimating] = useState(false);
  const [carouselDirection, setCarouselDirection] = useState<'next' | 'prev'>('next');
  const [expandedScrollTop, setExpandedScrollTop] = useState(0);
  const [isProgressUpdating, setIsProgressUpdating] = useState(false);
  const [isNewNotification, setIsNewNotification] = useState(false);
  const [isLeaving, setIsLeaving] = useState(false);
  const [viewedErrorNotifications, setViewedErrorNotifications] = useState<Set<string>>(new Set());
  const containerRef = useRef<HTMLDivElement>(null);
  const expandedRef = useRef<HTMLDivElement>(null);
  const autoCollapseTimerRef = useRef<NodeJS.Timeout | null>(null);
  const carouselTimerRef = useRef<NodeJS.Timeout | null>(null);
  const progressUpdateTimerRef = useRef<NodeJS.Timeout | null>(null);
  const errorViewTimerRef = useRef<NodeJS.Timeout | null>(null);
  const leaveTimerRef = useRef<NodeJS.Timeout | null>(null);

  // 检查是否有过渡中的通知
  const hasTransitioningNotification = useMemo(() => {
    return activeNotifications.some(state => state.phase === 'transitioning');
  }, [activeNotifications]);

  // 使用useMemo优化className计算，减少重新渲染
  const containerClassName = useMemo(() => {
    const classes = ['dynamic-island-container'];
    if (className) classes.push(className);
    if (isForceExpanded) classes.push('force-expanded');
    if (isProgressUpdating) classes.push('progress-updating');
    if (isNewNotification) classes.push('new-notification');
    if (hasTransitioningNotification) classes.push('transitioning');
    if (isLeaving) classes.push('leaving');
    return classes.join(' ');
  }, [className, isForceExpanded, isProgressUpdating, isNewNotification, hasTransitioningNotification, isLeaving]);

  // 过滤可见的活跃通知，限制数量并排序
  const visibleActiveNotifications = useMemo(() => {
    return activeNotifications
      .filter(state => state.isVisible && state.phase !== 'closed')
      .slice(0, maxNotifications)
      .sort((a, b) => {
        // 按优先级和时间排序
        const priorityA = a.notification.config?.priority || 0;
        const priorityB = b.notification.config?.priority || 0;
        if (priorityA !== priorityB) {
          return priorityB - priorityA; // 高优先级在前
        }
        return b.notification.startTime - a.notification.startTime; // 新的在前
      });
  }, [activeNotifications, maxNotifications]);

  // 通知队列管理 - 最多3个同时显示
  const displayNotifications = visibleActiveNotifications.slice(0, 3);
  const queuedNotifications = visibleActiveNotifications.slice(3);

  // 当前显示的通知（用于轮播）
  const currentNotification = enableCarousel && displayNotifications.length > 0
    ? displayNotifications[currentCarouselIndex % displayNotifications.length]
    : displayNotifications[0] || null;



  // 更新时间
  useEffect(() => {
    const timer = setInterval(() => {
      setCurrentTime(new Date());
    }, 1000);

    return () => clearInterval(timer);
  }, []);

  // 平滑轮播逻辑
  useEffect(() => {
    // 只有在有多个通知且未悬停时才启动轮播
    if (activeNotifications.length > 1 && !isHovered && !isCarouselAnimating) {
      carouselTimerRef.current = setTimeout(() => {
        setIsCarouselAnimating(true);
        setCarouselDirection('next');

        // 400ms后切换内容，与CSS动画时间同步
        setTimeout(() => {
          setCurrentCarouselIndex(prev => (prev + 1) % activeNotifications.length);

          // 再400ms后结束动画
          setTimeout(() => {
            setIsCarouselAnimating(false);
          }, 400);
        }, 200);
      }, 4000); // 4秒轮播间隔
    }

    return () => {
      if (carouselTimerRef.current) {
        clearTimeout(carouselTimerRef.current);
        carouselTimerRef.current = null;
      }
    };
  }, [activeNotifications.length, isHovered, currentCarouselIndex, isCarouselAnimating]);

  // 重置轮播索引当通知数量变化时
  useEffect(() => {
    if (currentCarouselIndex >= activeNotifications.length && activeNotifications.length > 0) {
      setCurrentCarouselIndex(0);
    }
  }, [activeNotifications.length, currentCarouselIndex]);

  // 页面加载时的状态恢复提示
  useEffect(() => {
    if (activeNotifications.length > 0) {
      // 检查是否有从存储恢复的通知
      const hasRestoredNotifications = activeNotifications.some(notification => {
        const timeSinceCreation = Date.now() - notification.notification.startTime;
        return timeSinceCreation > 10000; // 超过10秒的通知可能是恢复的
      });

      if (hasRestoredNotifications) {
        console.info('Dynamic Island: Restored notifications from previous session');
      }
    }
  }, [activeNotifications]);

  // 检测进度更新并触发闪烁动画 - 避免频繁触发
  const previousProgressRef = useRef<number | undefined>(undefined);
  const previousNotificationIdRef = useRef<string | undefined>(undefined);

  useEffect(() => {
    const currentProgress = currentNotification?.notification?.progress;
    const currentId = currentNotification?.notification?.id;
    const previousProgress = previousProgressRef.current;
    const previousId = previousNotificationIdRef.current;

    // 只有当进度实际变化且变化幅度大于2%时才触发动画，或者是新的通知
    if (currentProgress !== undefined &&
        ((previousProgress !== undefined && Math.abs(currentProgress - previousProgress) >= 2) ||
         (currentId !== previousId && currentId !== undefined))) {

      setIsProgressUpdating(true);

      // 清除之前的定时器
      if (progressUpdateTimerRef.current) {
        clearTimeout(progressUpdateTimerRef.current);
      }

      // 200ms后停止闪烁效果（进一步减少频率）
      progressUpdateTimerRef.current = setTimeout(() => {
        setIsProgressUpdating(false);
      }, 200);
    }

    previousProgressRef.current = currentProgress;
    previousNotificationIdRef.current = currentId;

    return () => {
      if (progressUpdateTimerRef.current) {
        clearTimeout(progressUpdateTimerRef.current);
      }
      if (leaveTimerRef.current) {
        clearTimeout(leaveTimerRef.current);
      }
    };
  }, [currentNotification?.notification?.progress, currentNotification?.notification?.id]);

  // 检测新通知并触发入场动画 - 只在真正有新通知时触发
  const previousNotificationCountRef = useRef(0);
  useEffect(() => {
    const currentCount = activeNotifications.length;
    const previousCount = previousNotificationCountRef.current;

    // 只有当通知数量增加时才触发新通知动画
    if (currentCount > previousCount && currentCount > 0) {
      setIsNewNotification(true);

      // 600ms后停止新通知动画
      const timer = setTimeout(() => {
        setIsNewNotification(false);
      }, 600);

      previousNotificationCountRef.current = currentCount;
      return () => clearTimeout(timer);
    }

    previousNotificationCountRef.current = currentCount;
  }, [activeNotifications.length]);

  // 组件卸载时清理所有定时器
  useEffect(() => {
    return () => {
      if (autoCollapseTimerRef.current) {
        clearTimeout(autoCollapseTimerRef.current);
      }
      if (carouselTimerRef.current) {
        clearTimeout(carouselTimerRef.current);
      }
      if (progressUpdateTimerRef.current) {
        clearTimeout(progressUpdateTimerRef.current);
      }
      if (errorViewTimerRef.current) {
        clearTimeout(errorViewTimerRef.current);
      }
      if (leaveTimerRef.current) {
        clearTimeout(leaveTimerRef.current);
      }
    };
  }, []);



  // 处理鼠标进入事件
  const handleMouseEnter = useCallback(() => {
    // 清除离开状态
    setIsLeaving(false);
    if (leaveTimerRef.current) {
      clearTimeout(leaveTimerRef.current);
      leaveTimerRef.current = null;
    }

    setIsHovered(true);
    setIsForceExpanded(true);

    // 清除轮播定时器（暂停轮播）
    if (carouselTimerRef.current) {
      clearTimeout(carouselTimerRef.current);
      carouselTimerRef.current = null;
    }

    // 清除之前的自动收缩定时器
    if (autoCollapseTimerRef.current) {
      clearTimeout(autoCollapseTimerRef.current);
      autoCollapseTimerRef.current = null;
    }

    // 清除错误查看定时器
    if (errorViewTimerRef.current) {
      clearTimeout(errorViewTimerRef.current);
      errorViewTimerRef.current = null;
    }

    // 标记当前错误通知为已查看
    if (activeNotifications.length > 0) {
      const currentState = activeNotifications[currentCarouselIndex];
      const currentNotification = currentState?.notification;

      if (currentNotification && (currentNotification.status === 'error' || currentNotification.status === 'failed')) {
        setViewedErrorNotifications(prev => new Set(prev).add(currentNotification.id));
      }
    }
  }, [activeNotifications, currentCarouselIndex]);

  // 处理鼠标离开事件 - 深度优化平滑过渡
  const handleMouseLeave = useCallback(() => {
    // 设置离开状态，触发平滑过渡
    setIsLeaving(true);
    setIsHovered(false);

    // 分阶段更新状态，确保CSS transition有足够时间
    leaveTimerRef.current = setTimeout(() => {
      setIsForceExpanded(false);
      // 清除离开状态
      setTimeout(() => {
        setIsLeaving(false);
      }, 400); // 等待transition完成
    }, 100); // 100ms延迟，让悬停效果先退出

    // 清除定时器
    if (autoCollapseTimerRef.current) {
      clearTimeout(autoCollapseTimerRef.current);
      autoCollapseTimerRef.current = null;
    }

    // 检查是否需要自动移除已查看的错误通知
    if (activeNotifications.length > 0) {
      const currentState = activeNotifications[currentCarouselIndex];
      const currentNotification = currentState?.notification;

      if (currentNotification &&
          (currentNotification.status === 'error' || currentNotification.status === 'failed') &&
          viewedErrorNotifications.has(currentNotification.id)) {

        // 错误通知已被查看，设置自动移除定时器
        errorViewTimerRef.current = setTimeout(() => {
          // 移除通知
          if (onRemoveNotification) {
            onRemoveNotification(currentNotification.id);
          }

          // 从已查看列表中移除
          setViewedErrorNotifications(prev => {
            const newSet = new Set(prev);
            newSet.delete(currentNotification.id);
            return newSet;
          });
        }, 2000); // 2秒后自动移除
      }
    }
  }, [activeNotifications, currentCarouselIndex, viewedErrorNotifications]);

  // 处理鼠标滚轮事件 - 切换通知
  const handleWheel = useCallback((event: React.WheelEvent) => {
    // 阻止事件冒泡，避免影响页面滚动
    event.preventDefault();
    event.stopPropagation();

    if (activeNotifications.length === 0) return;

    if (!isHovered && !isForceExpanded) {
      // 如果未展开，滚轮事件触发展开
      setIsForceExpanded(true);
      setIsHovered(true);

      // 清除轮播定时器
      if (carouselTimerRef.current) {
        clearTimeout(carouselTimerRef.current);
        carouselTimerRef.current = null;
      }
    } else if (activeNotifications.length > 1) {
      // 如果已展开且有多个通知，滚轮切换通知
      const scrollDelta = event.deltaY;

      // 添加切换动画
      setIsCarouselAnimating(true);

      if (scrollDelta > 0) {
        // 向下滚动 - 下一个通知
        setCarouselDirection('next');
        setTimeout(() => {
          setCurrentCarouselIndex(prev => (prev + 1) % activeNotifications.length);
          setTimeout(() => setIsCarouselAnimating(false), 200);
        }, 100);
      } else {
        // 向上滚动 - 上一个通知
        setCarouselDirection('prev');
        setTimeout(() => {
          setCurrentCarouselIndex(prev =>
            prev === 0 ? activeNotifications.length - 1 : prev - 1
          );
          setTimeout(() => setIsCarouselAnimating(false), 200);
        }, 100);
      }
    }
  }, [isHovered, isForceExpanded, activeNotifications.length]);

  // 使用原生事件监听器来设置passive: false
  useEffect(() => {
    const container = containerRef.current;
    if (!container) return;

    const wheelHandler = (event: WheelEvent) => {
      // 阻止默认滚动行为
      event.preventDefault();
      event.stopPropagation();

      // 触发React事件处理器
      const syntheticEvent = {
        preventDefault: () => {},
        stopPropagation: () => {},
        deltaY: event.deltaY,
      } as React.WheelEvent;

      handleWheel(syntheticEvent);
    };

    // 添加非被动事件监听器
    container.addEventListener('wheel', wheelHandler, { passive: false });

    return () => {
      container.removeEventListener('wheel', wheelHandler);
    };
  }, [handleWheel]);

  // 清理定时器
  useEffect(() => {
    return () => {
      if (autoCollapseTimerRef.current) {
        clearTimeout(autoCollapseTimerRef.current);
      }
      if (carouselTimerRef.current) {
        clearTimeout(carouselTimerRef.current);
      }
    };
  }, []);

  // 格式化时间显示
  const formatTime = useCallback((timestamp: number) => {
    // 添加防护措施
    if (!timestamp || isNaN(timestamp) || timestamp <= 0) {
      return '刚刚';
    }

    const now = Date.now();
    const diff = Math.floor((now - timestamp) / 1000);

    // 防止负数时间差
    if (diff < 0) {
      return '刚刚';
    }

    if (diff < 60) return `${diff}秒前`;
    if (diff < 3600) return `${Math.floor(diff / 60)}分钟前`;
    if (diff < 86400) return `${Math.floor(diff / 3600)}小时前`;
    return `${Math.floor(diff / 86400)}天前`;
  }, []);

  // 格式化当前时间显示
  const formatCurrentTime = useCallback((date: Date) => {
    return date.toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit',
      hour12: false
    });
  }, []);

  // 格式化详细时间信息
  const formatDetailedTime = useCallback((date: Date) => {
    return {
      time: date.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      }),
      date: date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        weekday: 'long'
      }),
      timestamp: date.getTime()
    };
  }, []);



  // Dynamic Island 常驻显示，即使没有通知也显示当前时间

  return (
    <div
      ref={containerRef}
      className={containerClassName}
      style={style}
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}
    >
      {/* 收起状态 - 胶囊形状（默认显示） */}
      <div className="dynamic-island-compact">
        <div className="compact-content-wrapper">
          <div
            className={`compact-content-item ${isCarouselAnimating ? 'exiting' : 'active'}`}
            key="stable-content"
          >
            {currentNotification?.notification ? (
              <>
                {/* 左侧内容组 */}
                <div className="compact-left-group">
                  <div
                    className="status-indicator"
                    data-status={currentNotification.notification.status}
                  />
                  <span className="compact-title">
                    {currentNotification.notification.title}
                  </span>
                </div>

                {/* 右侧内容组 */}
                <div className="compact-right-group">
                  {/* 显示通知计数器 */}
                  {activeNotifications.length > 1 && (
                    <span className="notification-counter">
                      {currentCarouselIndex + 1}/{activeNotifications.length}
                    </span>
                  )}
                </div>
              </>
            ) : (
              <>
                {/* 左侧内容组 */}
                <div className="compact-left-group">
                  <div
                    className="status-indicator"
                    data-status="running"
                  />
                  <span className="compact-title system-time-title">
                    {formatCurrentTime(currentTime)}
                  </span>
                </div>

                {/* 右侧内容组 */}
                <div className="compact-right-group">
                  <span className="compact-date">
                    {currentTime.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' })}
                  </span>
                </div>
              </>
            )}
          </div>
        </div>
      </div>

      {/* 展开状态 - 显示当前选中通知的详细信息 */}
      <div ref={expandedRef} className="dynamic-island-expanded">
        <div className="single-notification-detail">
          {currentNotification?.notification ? (
            // 显示当前选中通知的详细信息
            <div className="dynamic-island-item">
              <div className="dynamic-island-item-header">
                <div
                  className="status-indicator"
                  data-status={currentNotification.notification.status}
                />
                <span className="dynamic-island-item-title">
                  {currentNotification.notification.title}
                </span>
                {/* 将导航提示移到标题行右侧 */}
                {activeNotifications.length > 1 && (
                  <span className="nav-counter-inline">
                    {currentCarouselIndex + 1}/{activeNotifications.length}
                  </span>
                )}
              </div>

              {currentNotification.notification.description && (
                <div className="dynamic-island-item-description">
                  {currentNotification.notification.description}
                  {/* 将队列指示器移到描述末尾 */}
                  {queuedNotifications.length > 0 && (
                    <span className="queue-indicator-inline">
                      {' '}+{queuedNotifications.length} 等待中
                    </span>
                  )}
                </div>
              )}

              {currentNotification.notification.progress !== undefined && (
                <div className="dynamic-island-item-progress">
                  <div className="progress-bar">
                    <div
                      className="progress-fill"
                      style={{
                        width: `${currentNotification.notification.progress}%`,
                        backgroundColor: currentNotification.notification.status === 'error' ? '#FF3B30' :
                                       currentNotification.notification.status === 'warning' ? '#FF9500' :
                                       currentNotification.notification.status === 'success' ? '#34C759' : '#007AFF',
                      }}
                    />
                  </div>
                </div>
              )}




            </div>
          ) : (
            // 没有通知时显示详细时间信息
            <div className="dynamic-island-item system-time-panel">
              <div className="dynamic-island-item-header">
                <div className="status-indicator running" />
                <span className="dynamic-island-item-title system-time-main">
                  {formatDetailedTime(currentTime).time}
                </span>
              </div>
              <div className="dynamic-island-item-description system-time-detail">
                <div className="time-detail-row">
                  <span className="time-label">日期</span>
                  <span className="time-value">{formatDetailedTime(currentTime).date}</span>
                </div>
                <div className="time-detail-row">
                  <span className="time-label">时间戳</span>
                  <span className="time-value">{formatDetailedTime(currentTime).timestamp}</span>
                </div>
                <div className="time-detail-row">
                  <span className="time-label">时区</span>
                  <span className="time-value">UTC+8 (北京时间)</span>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default memo(DynamicIslandNotification);
